<?php

namespace app\admin\service;

use app\admin\model\Goods;

class GoodsService
{
    public function getGoodsList()
    {
        $model = new Goods();
        $goods = $model->field('id,sort,goods_name,main_image,total_stock,total_sale,status,create_time,update_time')->with(['goodsContent','items','category'=> function($query){
            $query->field('id,name');
        }])->paginate(10);

        return $goods;
    }

    public function getGoodsOptions()
    {
        $model = new Goods();
        $goodsOptions = $model->field('id,goods_name,main_image,total_stock,goods_attr')->withAttr('goods_attr',function($value){
            return $value;

        })->with('items')->where('status',1)->select();

        return $goodsOptions;
    }

    public function findGoods($id)
    {
        $model = new Goods();
        $goods = $model->withOutField('create_time,update_time,delete_time')
                        ->with(['goodsContent','items'])
                        ->find($id);
        return $goods;
    }


    public function saveGoods($data)
    {   
        $skus = $data['skus'];
        $data['market_low_price'] = min(array_column($skus,'market_price'));
        $data['sell_low_price'] = min(array_column($skus,'sell_price'));
        $data['total_stock'] =  array_sum(array_column($skus,'stock'));


        $goods = Goods::create($data);
        $goods->goodsContent()->save($data);
        $goods->items()->saveAll($skus);

        return $goods['id'];
    }

    public function updateGoods($data)
    {   
        $skus = $data['skus'];
        $data['market_low_price'] = min(array_column($skus,'market_price'));
        $data['sell_low_price'] = min(array_column($skus,'sell_price'));
        $data['total_stock'] =  array_sum(array_column($skus,'stock'));
        
        $goods = Goods::update($data);

        $goods->goodsContent->where('goods_id',$data['id'])->update(['content' => $data['content']]);
        
        $goods->items()->saveAll($skus);

        return $goods['id'];
    }

    // 获取sku中的最小市场价和售卖价,以及库存


}